<template>
  <div class="dialog">
    <div class="content">
      <p>{{type === 'add'?'新增联系人':'修改联系人'}}</p>
      <br />
      <br />
      <input type="text" placeholder="姓名" v-model="name">
      <br />
      <br />
      <input type="text" placeholder="电话" v-model="phone">
      <br />
      <br />
      <button v-if="type === 'add'" @click="add">提交</button>
      <button v-else @click="edit">修改</button>
      <button @click="cancel">取消</button>
    </div>
  </div>
</template>

<script>
export default {
  props: ['type'],
  data() {
    return {
      name: '',
      phone: '',
      index: 0
    }
  },
  methods: {
    // 给输入框赋值
    setVal(obj) {
      // console.log(obj);
      this.name = obj.name;
      this.phone = obj.phone;
      // 保存当前修改的值，-1表示新增，大于等于0表示修改
      this.index = obj.index;
    },
    // 取消
    cancel() {
      // 清空输入框
      this.name = '';
      this.phone = '';
      this.$emit('close');
    },
    // 提交，新增联系人，加入到父组件的数组中
    add() {
      let info = {name: this.name, phone: this.phone};
      // 子传父
      this.$emit('add', info);
      this.cancel();
    },
    edit() {
      // console.log(this.name);
      // console.log(this.phone);
      // console.log(this.index);
      let obj = {name: this.name, phone: this.phone}
      this.$emit('edit', this.index, obj);
      this.cancel();
    }
  },
}
</script>

<style>
  .dialog {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    background-color: rgba(240, 240, 240, 0.8);
  }
  .content {
    width: 500px;
    height: 250px;
    background-color: #fff;
    margin: 100px auto 0;
    border: 1px solid #666;
  }
</style>